package edu.biwu.schema.json;

import cn.hutool.json.JSONUtil;
import edu.biwu.Student;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 利用hutool实现java对象和json数据的互转
 */
public class JSONTest01 {
    /*将一个java对象转换成json格式*/
    @Test
    public void testObjectToJson(){
        Student student = new Student(20131210, "杨过", "男", 25);
        String jsonStr = JSONUtil.toJsonStr(student);
        System.out.println(jsonStr);
    }
    /*将一个json字符转换成java对象*/
    @Test
    public void testJsonToObject(){
        String jsonStr = "{'sno':20131210,'name':'杨过','gender':'男','age':25}";
        String jsonStr2 = "{\"sno\":20131210,\"name\":\"杨过\",\"gender\":\"男\",\"age\":25}";
        Student bean = JSONUtil.toBean(jsonStr, Student.class);
        System.out.println(bean);
    }
    /*将一个集合转换成json*/
    @Test
    public void testListToJson(){
        List<Student> students = Arrays.asList(
                new Student(20131210, "杨过", "男", 25),
                new Student(20130209, "小龙女", "女", 20)
        );
        System.out.println(JSONUtil.toJsonStr(students));
        System.out.println(JSONUtil.toJsonPrettyStr(students));
    }

    /*将一个json转换成集合*/
    @Test
    public void testJsonToList(){
        String jsonStr = "[{\"sno\":20131210,\"name\":\"杨过\",\"gender\":\"男\",\"age\":25},{\"sno\":20130209,\"name\":\"小龙女\",\"gender\":\"女\",\"age\":20}]";
        JSONUtil.parseArray(jsonStr).toList(Student.class).forEach(System.out::println);
    }

    /*将map对象转换成Json串*/
    @Test
    public void testMapToJson(){
        List<Student> students = Arrays.asList(
                new Student(20131210, "杨过", "男", 25),
                new Student(20130209, "小龙女", "女", 20)
        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + " ", stu -> stu));
        System.out.println(JSONUtil.toJsonStr(map));
        System.out.println(JSONUtil.toJsonPrettyStr(map));
    }
}
